package com.xxx.springboot.service.impl;

import com.xxx.springboot.pojo.bean.PubSubMsg;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * 【Redis 发布/订阅】 1. 发布/订阅service服务
 *
 * @author guwq
 * @since 2021/4/28
 */
@Slf4j
@Service
public class RedisPubsubService {

    private static final String TOPIC_NAME = "topicA";

    @Autowired
    private RedissonClient redissonClient;

    // 发布
    public long publish(PubSubMsg msg){
        log.info("开始发布消息：主题={}，内容={}", TOPIC_NAME, msg);
        RTopic topic = redissonClient.getTopic(TOPIC_NAME);
        long receivedClientNum = topic.publish(msg);
        log.info("receivedClientNum={}", receivedClientNum);
        if(receivedClientNum<1){ // receivedClientNum为成功订阅到消息的客户端数量
            log.error("发布消息失败, msg={}", msg);
        }
        return receivedClientNum;
    }

    // 订阅（必须有订阅方才能发布成功）
    @PostConstruct  // @PostConstruct的方法不能有参数
    public void subscribe1(){
        // 获取主题
        RTopic topic = redissonClient.getTopic(TOPIC_NAME);
        // 创建订阅事件监听器
        MessageListener<PubSubMsg> listener = new MessageListener<PubSubMsg>() {
            @Override
            public void onMessage(String channel, PubSubMsg msg) {
                log.info("订阅方1接受到消息：主题={}，渠道={}，内容={}", TOPIC_NAME, channel, msg.toString());
            }
        };
        // 将监听器绑定到主题
        topic.addListener(listener);
    }

//    // 同一个topic，可以有多个订阅方
//    @PostConstruct
//    public void subscribe2(){
//        // 获取主题
//        RTopic topic = redissonClient.getTopic(TOPIC_NAME);
//        // 创建订阅事件监听器
//        MessageListener<PubSubMsg> listener = new MessageListener<PubSubMsg>() {
//            @Override
//            public void onMessage(String channel, PubSubMsg msg) {
//                log.info("订阅方2接受到消息：主题={}，渠道={}，内容={}", TOPIC_NAME, channel, msg.toString());
//            }
//        };
//        // 将监听器绑定到主题
//        topic.addListener(listener);
//    }

}
